import re
import pandas as pd
from enum import Enum, auto
from PIL import Image as PILImage
from ..utils import LOG

class ContentType(Enum):
    TEXT = auto()
    TABLE = auto()
    IMAGE = auto()

class Content:
    def __init__(self, content_type, original, translation=None):
        self.content_type = content_type
        self.original = original
        self.translation = translation
        self.status = False
        
        # 新增布局相关属性
        self.x = 0      # X坐标（毫米）
        self.y = 0      # Y坐标（毫米）
        self.font_size = 12  # 字体大小
        self.font_name = "SimSun"  # 字体名称

    def set_translation(self, translation, status):
        if not self.check_translation_type(translation):
            raise ValueError(f"Invalid translation type. Expected {self.content_type}, but got {type(translation)}")
        self.translation = translation
        self.status = status

    def check_translation_type(self, translation):
        if self.content_type == ContentType.TEXT and isinstance(translation, str):
            return True
        elif self.content_type == ContentType.TABLE and isinstance(translation, list):
            return True
        elif self.content_type == ContentType.IMAGE and isinstance(translation, PILImage.Image):
            return True
        return False


class TableContent(Content):
    def __init__(self, data, translation=None):
        df = pd.DataFrame(data)

        # Verify if the number of rows and columns in the data and DataFrame object match
        if len(data) != len(df) or len(data[0]) != len(df.columns):
            raise ValueError("The number of rows and columns in the extracted table data and DataFrame object do not match.")
        
        super().__init__(ContentType.TABLE, df)

    def set_translation(self, translation, status):
        try:
            if not isinstance(translation, str):
                raise ValueError(f"Invalid translation type. Expected str, but got {type(translation)}")

            LOG.debug(translation)
            
            # 优化点1：使用更可靠的分割方式（支持包含空格的单元格）
            table_data = []
            max_columns = 0
            for row in translation.strip().split('\n'):
                # 使用修正后的正则表达式（简化引号处理）
                cells = re.findall(r'((?:[^\s"\'\\]|\\.|"(?:\\"|[^"])*"|\'(?:\\\'|[^\'])*\')+)', row)
                # 去除外层引号并处理转义字符
                cleaned_cells = [
                    re.sub(r'\\(.)', r'\1', cell.strip('"\'')).strip() 
                    for cell in cells
                ]
                table_data.append(cleaned_cells)
                max_columns = max(max_columns, len(cleaned_cells))

            # 优化点2：自动对齐列数
            aligned_data = []
            for row in table_data:
                # 填充缺失列
                aligned_row = row + [''] * (max_columns - len(row))
                aligned_data.append(aligned_row[:max_columns])  # 确保不超过最大列数

            # 优化点3：动态生成表头（避免硬编码列数）
            headers = [f"列{i+1}" for i in range(max_columns)]
            translated_df = pd.DataFrame(aligned_data[1:], columns=headers) if max_columns >0 else pd.DataFrame()

            self.translation = translated_df
            self.status = status
        except Exception as e:
            LOG.error(f"表格处理失败: {str(e)} | 原始数据: {translation}")
            self.translation = None
            self.status = False

    def __str__(self):
        return self.original.to_string(header=False, index=False)

    def iter_items(self, translated=False):
        target_df = self.translation if translated else self.original
        for row_idx, row in target_df.iterrows():
            for col_idx, item in enumerate(row):
                yield (row_idx, col_idx, item)

    def update_item(self, row_idx, col_idx, new_value, translated=False):
        target_df = self.translation if translated else self.original
        target_df.at[row_idx, col_idx] = new_value

    def get_original_as_str(self):
        return self.original.to_string(header=False, index=False)
    
    def set_position(self, x, y):
        self.x = x
        self.y = y

    def set_font(self, size, name):
        self.font_size = size
        self.font_name = name